package com.gxc.controller;

import com.alibaba.fastjson.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传Controller.
 *
 * @author 宫新程
 * @since 2019/2/28 22:28
 */
@Slf4j
@Controller
public class UploadController {

  @Value("${ylh.upload.path}")
  private String path;

  @Value("${java.io.tmpdir}")
  private String tmpDir;

  /**
   * 单文件上传.
   *
   * @return
   */
  @PostMapping("/upload")
  public String upload(MultipartFile file) throws IOException {
    String contentType = file.getContentType();
    String name = file.getName();
    String originalFilename = file.getOriginalFilename();
    long size = file.getSize();
    System.out.println("contentType：" + contentType);
    System.out.println("name：" + name);
    System.out.println("originalFilename：" + originalFilename);
    System.out.println("size：" + size);
    InputStream inputStream = file.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
      sb.append(line);
    }
    System.out.println(sb.toString());
    String encode = Base64Utils.encodeToString(file.getBytes());
    System.out.println(encode);
    file.transferTo(new File("D:\\", file.getOriginalFilename()));
    return "index";
  }

  /**
   * 多文件上传.
   *
   * @param file
   * @return
   * @throws Exception
   */
  @PostMapping("/uploadAll")
  public String uploadAll(List<MultipartFile> file) throws Exception {
    int size = file.size();
    System.out.println("size：" + size);
    List<String> collect =
        file.stream()
            .map(
                e -> {
                  String[] split = e.getOriginalFilename().split("/");
                  return split[0];
                })
            .distinct()
            .collect(Collectors.toList());
    System.out.println(collect);
    File file1 = new File("E:\\test\\" + collect.get(0));
    if (!file1.exists()) {
      file1.mkdirs();
    }
    for (MultipartFile e : file) {
      String contentType = e.getContentType();
      String name = e.getName();
      String originalFilename = e.getOriginalFilename();
      long fileSize = e.getSize();
      System.out.println("contentType：" + contentType);
      System.out.println("name：" + name);
      System.out.println("originalFilename：" + originalFilename);
      System.out.println("fileSize：" + fileSize);
      System.out.println("========================");
      try {
        e.transferTo(new File("E:\\test", e.getOriginalFilename()));
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
    return "index";
  }

  @PostMapping("/zip")
  @ResponseBody
  private Map<String, String> uploadZip(MultipartFile file) throws Exception {
    System.out.println("临时文件目录：" + tmpDir);
    // 判断临时文件夹是否存在
    File localFile = new File(tmpDir);
    if (!localFile.exists()) {
      localFile.mkdirs();
    }
    // 存放到临时文件目录
    file.transferTo(new File(tmpDir, file.getOriginalFilename()));

    // 读取存放在临时文件目录的文件
    File zipFile = new File(tmpDir, file.getOriginalFilename());
    // 获取压缩文件中的内容
    Map<String, String> map = readZipFile(zipFile);

    map.forEach(
        (k, v) -> {
          if (k.lastIndexOf(".json") > 0) {
            HashMap hashMap = JSONObject.parseObject(v, HashMap.class);
            String s = JSONObject.toJSONString(hashMap);
            System.out.println(s);
          }
        });
    //    zipFile.delete();
    return map;
  }

  /** 读取zip内容. */
  private static Map<String, String> readZipFile(File file) throws Exception {
    ZipFile zf = new ZipFile(file);
    InputStream in = new BufferedInputStream(new FileInputStream(file));
    ZipInputStream zin = new ZipInputStream(in);
    ZipEntry ze;

    Map<String, String> map = new HashMap<>();
//    while ((ze = zin.getNextEntry()) != null) {
//      if (ze.isDirectory() || ze.getSize() <= 0) {
//        continue;
//      }
//      if (ze.getName().lastIndexOf(".json") > 0) {
//        BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));
//        String line;
//        StringBuilder sb = new StringBuilder();
//        while ((line = br.readLine()) != null) {
//          sb.append(line);
//        }
//        br.close();
//        map.put(ze.getName(), sb.toString());
//      } else {
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        InputStream inputStream = zf.getInputStream(ze);
//        int len = 0;
//        byte[] bytes = new byte[1024];
//        while ((len = inputStream.read(bytes)) != -1) {
//          bos.write(bytes, 0, len);
//        }
//        byte[] picBytes = bos.toByteArray();
//        String baseStr = Base64Utils.encodeToString(picBytes);
//        map.put(ze.getName(), baseStr);
//      }
//    }
    zf.close();
    in.close();
    zin.closeEntry();
    return map;
  }
}
